<?php

declare(strict_types=1);

namespace cosy\framework\exceptions;

use cosy\framework\enums\CodeEnum;
use app\ExceptionHandle;
use stdClass;
use thans\jwt\exception\JWTException;
use thans\jwt\exception\TokenExpiredException;
use think\exception\ValidateException;
use think\Response;
use Throwable;

/**
 * ClassName CosyException
 * Description TODO
 * Author BTC
 * Date 2023/11/7 16:52
 **/
class CosyException extends ExceptionHandle
{
    public function render($request, Throwable $e): Response
    {
        if ($e instanceof ValidateException) {
            return json([
                'code' => 422,
                'msg' => lang($e->getMessage()),
                'result' => new stdClass()
            ]);
        }

        if ($e instanceof UnprocessableException) {
            return json([
                'code' => $e->getCode(),
                'msg' => lang($e->getMessage()),
                'result' => $e->result
            ], $e->status);
        }

        if($e instanceof TokenExpiredException){
            return json([
                'code' => CodeEnum::TOKEN_EXPIRED,
                'msg' => lang('登录已失效'),
                'result' => new stdClass()
            ]);
        }


        if($e instanceof JWTException){
            return json([
                'code' => CodeEnum::TOKEN_EXPIRED,
                'msg' => lang('登录已失效'),
                'result' => new stdClass()
            ]);
        }

        return json([
            'code' => 422,
            'msg' => $e->getMessage(),
            'result' => new stdClass()
        ]);
    }
}